const App = getApp();
import Notify from '../../dist/notify/notify';
import Toast from '../../dist/toast/toast';

Page({
    data: {
        imgUrl:App.globalData.imgUrl,
        isLoading: true,
        reLoading: false,
        features_id: 0,
        isFullSucreen: App.globalData.isFullSucreen, //判断机型
        hara_url: '',
        ad_img: '',
        file_id: 0,
        tmp_img: '',
        wechatUrl: '',
        aliUrl: '',
        share_title: '',
        ad_img_list: [],
        inputLists: [{}],
        videoSrc: '',
        videoType: '',
        replace: {
            file: '',
            text: '',
        },
        videoAd: null,
        isTipsShow: false,
        switch1Checked: false,
        switch2Checked: false,
        radioChecked: 'r1', // r1打开视频  r2一键关注
        isTipsVideoShow: false,
    },

    onLoad: function (options) {
        let _this = this;
        _this.setData({
            features_id: options.features_id
        })
        _this.getFeatures();
        _this.adSetting();
    },

    onShow() {

    },

    // switch外部跳转切换
    switch1Change(e) {
        this.setData({
            switch1Checked: e.detail.value
        })
    },

    switch2Change(e) {
        this.setData({
            switch2Checked: e.detail.value
        })
    },

    radioChange(e) {
        console.log(e);
        this.setData({
            radioChecked: e.detail.value
        })
    },

    // 获取广告设置
    adSetting() {
        let _this = this;
        App._get('user.advertising/setting', {}, res => {
            _this.setData(res.data);
        });
    },

    // 显示提示
    tips() {
        this.setData({
            isTipsShow: true
        })
    },

    tipsVideo() {
        this.setData({
            isTipsVideoShow: true
        })
    },

    // 关闭提示
    onTipsClose() {
        this.setData({
            isTipsShow: false,
            isTipsVideoShow: false
        })
    },

    // 加载插屏广告
    getAd() {
        let _this = this;
        let videoAd = null
        let index = Math.floor((Math.random() * _this.data.detail.ad_unit.length))
        // 在页面onLoad回调事件中创建激励视频广告实例
        if (wx.createRewardedVideoAd) {
            videoAd = wx.createRewardedVideoAd({
                adUnitId: _this.data.detail.ad_unit[index]
            })
            videoAd.onLoad(() => {
                Toast.clear();
            })
            videoAd.onError((err) => {
                Toast.clear();
            })
            videoAd.onClose((res) => {
                if (!videoAd) return
                videoAd.offClose()
                Toast.clear();
                if (res && res.isEnded) {
                    // 奖励用户次数
                    Toast.loading({
                        duration: 0,
                        forbidClick: true,
                        message: "发放奖励中",
                        selector: '#custom-selector',
                    });
                    App._get('user.advertising/reward', {
                        ad_id: _this.data.detail.ad_unit[index],
                        features_id: _this.data.features_id,
                    }, res => {
                        wx.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }, false, () => {
                        Toast.clear();
                    });
                }
            })
        }
        // 用户触发广告后，显示激励视频广告
        if (videoAd) {
            videoAd.show().catch(() => {
                // 失败重试
                videoAd.load()
                    .then(() => videoAd.show())
                    .catch(err => {
                        console.log('激励视频 广告显示失败')
                    })
            })
        }
    },

    // 播放激励视频
    playAd() {
        let _this = this;
        wx.showModal({
            title: '观看广告赠送次数',
            content: '观看完整激励视频将免费获得' + _this.data.ad_balance + '次奖励,每天最大获得奖励次数为' + _this.data.ad_today_num + '次!',
            cancelText: '我再想想',
            confirmText: '进入广告',
            success(res) {
                if (res.confirm) {
                    Toast.loading({
                        duration: 0,
                        forbidClick: true,
                        message: "视频加载中",
                        selector: '#custom-selector',
                    });
                    _this.getAd();
                }
            }
        })

    },

    // 调起扫码
    qrcodeScanning() {
        let _this = this;
        _this.setData({
            reLoading: true
        })
        wx.scanCode({
            success(res) {
                console.log(res.result);
                if (res.result.indexOf('http') == -1) {
                    Notify({type: 'primary', message: '这不是一个标准的链接二维码'});
                    _this.setData({
                        'replace.text': ''
                    })
                    return false;
                }
                _this.setData({
                    'replace.text': res.result
                })
            },
            fail(res) {
                _this.setData({
                    'replace.text': ''
                })
                wx.showToast({
                    title: '扫码失败',
                    icon: 'none'
                })
            },
            complete() {
                _this.setData({
                    reLoading: false
                })
            },
        })
    },

    // 调起扫码
    scanning() {
        let _this = this;
        _this.setData({
            reLoading: true
        })
        wx.scanCode({
            success(res) {
                _this.setData({
                    hara_url: res.result
                })
                console.log(res.result);
            },
            fail(res) {
                _this.setData({
                    hara_url: ''
                })
                wx.showToast({
                    title: '扫码失败',
                    icon: 'none'
                })
            },
            complete() {
                _this.setData({
                    reLoading: false
                })
            },
        })
    },

    // 收款码扫码
    paymentScanning() {
      console.log('收款码扫码')
        let _this = this;
        _this.setData({
            reLoading: true
        })
        wx.scanCode({
            success(res) {
                _this.setData({
                    hara_url: res.result
                })
                console.log(res.result);
                if (res.result.indexOf('wxp://') != -1) {
                    _this.setData({
                        wechatUrl: res.result
                    })
                }
                if (res.result.indexOf('alipay.com') != -1) {
                    _this.setData({
                        aliUrl: res.result
                    })
                }
                if (res.result.indexOf('payapp.weixin.qq.com') != -1) {
                    // wx.showModal({
                    //     title: '温馨提示',
                    //     content: '这是一个微信商业版收款码,请使用二维码赋能进行操作!',
                    //     showCancel: false,
                    // })
                    _this.setData({
                        wechatUrl: res.result
                    })
                }
            },
            fail(res) {
                _this.setData({
                    hara_url: ''
                })
                wx.showToast({
                    title: '扫码失败',
                    icon: 'none'
                })
            },
            complete() {
                _this.setData({
                    reLoading: false
                })
            },
        })
    },

    // 获取赋能模块信息
    getFeatures() {
        let _this = this;
        App._get('features/detail', {
            features_id: _this.data.features_id
        }, res => {
            _this.setData(res.data)
            wx.setNavigationBarTitle({
                title: res.data.detail.title
            })
            if (res.data.detail.type.value == 10 || res.data.detail.type.value == 40 || res.data.detail.type.value == 51) {
                _this.getAdvertising();
            }
        }, false, () => {
            _this.setData({
                isLoading: false,
                reLoading: false,
            })
        });
    },

    checkGh(e) {
        if (e.detail.value.indexOf('gh_') == -1) {
            Notify({type: 'primary', message: '小程序原始ID不正确'});
            return false
        }
    },

    // 获取默认广告图片
    getAdvertising() {
        let _this = this;
        App._get('Advertising/lists', {}, res => {
            _this.setData({
                ad_img_list: res.data.list
            })
        });
    },

    // 上传原图
    chooseImageOriginal() {
        let _this = this;
        wx.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success: function (res) {
                _this.getResourcesUpload(res.tempFilePaths[0]);
            }
        });
    },

    // 提交替换
    replaceSubmit() {
        let _this = this;
        if (!_this.data.replace.file.length) {
            Notify({type: 'primary', message: '请上传原图'});
            return false
        }
        if (!_this.data.replace.text.length) {
            Notify({type: 'primary', message: '请扫描二维码'});
            return false
        }
        _this.setData({
            reLoading: true
        })
        App._post_form('generate/addReplaceImg', {
            bg: _this.data.replace.file,
            text: _this.data.replace.text,
            type: _this.data.detail.type.value,
        }, res => {
            wx.redirectTo({
                url: './replace?key=' + res.data.key
            })
        }, false, () => {
            _this.setData({
                reLoading: false
            })
        });
    },

    // 获取图片替换
    getResourcesUpload(img) {
        let _this = this;
        let params = {
            wxapp_id: App.getWxappId(),
            token: wx.getStorageSync('token')
        };
        _this.setData({
            reLoading: true,
        })
        wx.uploadFile({
            url: App.api_root + 'upload/getResourcesUpload',
            filePath: img,
            name: 'image',
            formData: params,
            success: function (res) {
                let result = typeof res.data === "object" ? res.data : JSON.parse(res.data);
                console.log(result);
                if (result.code == 0) {
                    wx.showModal({
                        title: '友情提示',
                        content: result.msg,
                        showCancel: false,
                    })
                }
                if (result.code == -1) {
                    App.doLogin();
                }
                _this.setData({
                    'replace.file': result.data ? result.data.file : '',
                    reLoading: false,
                })
            }
        });
    },

    // 引导页图片上传
    chooseImage() {
        let _this = this;
        wx.chooseImage({
            count: 1,
            sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                console.log(res.tempFilePaths[0]);
                _this.setData({
                    'detail.guide.file_path': res.tempFilePaths[0],
                    tmp_img: res.tempFilePaths[0],
                })
                _this.uploadFile();
            }
        });
    },

    // 自定义广告图片上传
    chooseAdImage() {
        let _this = this;
        wx.chooseImage({
            count: 1,
            sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                console.log(res.tempFilePaths[0]);
                _this.setData({
                    tmp_img: res.tempFilePaths[0],
                })
                _this.uploadFile();
            }
        });
    },

    // 执行图片上传
    uploadFile() {
        let _this = this;
        let params = {
            wxapp_id: App.getWxappId(),
            token: wx.getStorageSync('token')
        };
        _this.setData({
            reLoading: true,
        })
        wx.uploadFile({
            url: App.api_root + 'upload/image',
            filePath: _this.data.tmp_img,
            name: 'iFile',
            formData: params,
            success: function (res) {
                let result = typeof res.data === "object" ? res.data : JSON.parse(res.data);
                _this.setData({
                    file_id: result.data.file_id,
                    ad_img: result.data.file_path,
                    reLoading: false,
                })
            }
        });
    },

    // 提交赋能
    submit(e) {
        let _this = this,
            value = e.detail.value;
        // 表单校验
        if (!_this._onVerify(value)) {
            return false
        }
        // 二维码扫码赋能需验证自定义中转页
        if (_this.data.detail.type.value == 20 && !_this.data.tmp_img.length) {
            // 否则使用默认的引导页
            _this.setData({
                file_id: _this.data.detail.guide.file_id
            })
        }
        if (_this.data.detail.type.value == 20) {
            value.file_id = _this.data.file_id
            value.hara_url = _this.data.hara_url
        }
        value.videoType = _this.data.videoType;
        value.wechatUrl = _this.data.wechatUrl
        value.aliUrl = _this.data.aliUrl
        value.ad_img = _this.data.ad_img
        // 小程序赋能中转页图片
        if (_this.data.detail.type.value == 51 && !_this.data.tmp_img.length) {
            value.ad_img = _this.data.detail.guide.file_path
        }
        value.type = _this.data.detail.type.value
        console.log('value',value)
        // 提交表单
        _this.setData({
            reLoading: true,
        })
        App._post_form('generate/create', value, res => {
            if (res.code == 201) {
                wx.showModal({
                    title: '温馨提示',
                    content: '您的次数不足且不是VIP身份!',
                    showCancel: false,
                    success(res) {
                    }
                })

            } else {
                wx.redirectTo({
                    url: '/pages/generate/detail?key=' + res.data.key
                })
            }
        }, false, () => {
            _this.setData({
                reLoading: false
            })
        })

    },


    // 表单验证
    _onVerify(data) {
        let _this = this;
        if (_this.data.detail.type.value == 20 && !_this.data.hara_url.length) {
            Notify({type: 'primary', message: '请扫描或选择一个二维码'});
            return false
        }
        if (_this.data.detail.type.value == 30) {
            if (!_this.data.wechatUrl.length && !_this.data.aliUrl.length) {
                Notify({type: 'primary', message: '请扫描或选择一个收款码'});
                return false
            }
        }
        if (_this.data.detail.type.value == 50 && !_this.data.videoSrc.length) {
            Notify({type: 'primary', message: '请填写视频分享链接'});
            return false
        }
        if ((_this.data.detail.type.value == 10 || _this.data.detail.type.value == 40) && !data.hara_url.length) {
            Notify({type: 'primary', message: '请填写网站链接'});
            return false
        }
        if ((_this.data.detail.type.value == 51) && !data.hara_url.length) {
            Notify({type: 'primary', message: '请填写小程序原始ID'});
            return false
        }
        let reg = /(http|https):\/\/([\w.]+\/?)\S*/;
        if ((_this.data.detail.type.value == 10 || _this.data.detail.type.value == 40) && !reg.test(data.hara_url)) {
            Notify({type: 'primary', message: '网站链接不是一个标准的url格式'});
            return false
        }
        if (!data.command.length) {
            Notify({type: 'primary', message: '请输入赋能内容'});
            return false
        }
        if ((_this.data.detail.type.value == 20) && !data.title.length) {
            Notify({type: 'primary', message: '请输入中转页标题'});
            return false
        }
        return true;
    },

    // 公众号链接失去焦点自动获取标题
    onUrlBlur(e) {
        let _this = this,
            url = e.detail.value;
        let reg = /(http|https):\/\/([\w.]+\/?)\S*/;
        if (!reg.test(url)) {
            Notify({type: 'primary', message: '网站链接不是一个标准的url格式'});
            return false
        }
        _this.setData({
            reLoading: true,
        })
        App._post_form('generate/getTitle', {
            url: url
        }, res => {
            _this.setData({
                share_title: res.data.title
            })
        }, false, () => {
            _this.setData({
                reLoading: false,
            })
        });

    },


    // 选择广告图片
    selectAdImg(e) {
        let _this = this;
        let item = e.currentTarget.dataset.item;
        _this.setData({
            ad_img: item.image.file_path,
            tmp_img: item.image.file_path,
        })
    },


    clearImg() {
        this.setData({
            ad_img: '',
            tmp_img: '',
        })
        // let _this = this
        // if (_this.data.videoAd) {
        //     _this.data.videoAd.show().catch(() => {
        //         // 失败重试
        //         _this.data.videoAd.load()
        //             .then(() => _this.data.videoAd.show())
        //             .catch(err => {
        //                 console.log('激励视频 广告显示失败')
        //             })
        //     })
        // }
    },

    // 添加列表
    addList() {
        var inputLists = this.data.inputLists;
        var newData = {};
        inputLists.push(newData);//实质是添加inputLists数组内容，使for循环多一次
        this.setData({
            inputLists: inputLists,
        })

    },

    // 删除列表
    delList() {
        var inputLists = this.data.inputLists;
        if (inputLists.length <= 1) {
            wx.showToast({
                title: '无法删除',
                icon: 'none'
            })
            return false
        }
        inputLists.pop();      //实质是删除inputLists数组内容，使for循环少一次
        this.setData({
            inputLists: inputLists,
        })
    },

    // 获取视频地址
    getVideoSrc(e) {
        let _this = this;
        _this.setData({
            reLoading: true,
        })
        App._post_form('Generate/getVideoSrc', {
            url: e.detail.value
        }, res => {
            if (res.code == 1) {
                _this.setData({
                    videoHaraUrl: e.detail.value,
                    videoSrc: res.data.src,
                    videoType: res.data.type,
                })
            }
        }, false, () => {
            _this.setData({
                reLoading: false,
            })
        });
    },


});
